package com.missyoubug.easyjtest.service.impl;

import com.missyoubug.easyjtest.dao.EasyTestDao;
import com.missyoubug.easyjtest.entity.EasyTestEntity;
import com.missyoubug.easyjtest.entity.EasyTestInfoEntity;
import com.missyoubug.easyjtest.service.EasyTestService;
import com.missyoubug.easyjtest.util.EmptyChecker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class EasyTestServiceImpl implements EasyTestService {
    @Autowired(required=true)
    private EasyTestDao testDao;

    @Override
    public void insertInvocation(EasyTestInfoEntity record) {
        record.setAddTime(LocalDateTime.now());

        // 插入新记录之前，先检查记录总数
        int count = testDao.getRecordCount();
        if (count >= 200) {
            // 如果已有100条或更多记录，则删除最旧的一条
            testDao.deleteOldestRecord();
        }

        // 插入新记录
        testDao.insertInvocation(record);
    }


    public EasyTestEntity getAllInvocations() {
        List<EasyTestInfoEntity> allInvocations = testDao.getAllInvocations();
        EasyTestEntity easyTest = new EasyTestEntity();
        easyTest.setHistoryInfo(htmlConsole(allInvocations));
        return easyTest;
    }


    private String htmlConsole(List<EasyTestInfoEntity> testList) {
        StringBuilder html = new StringBuilder();

        if (EmptyChecker.isEmpty(testList)) {

            html.append("<p> No historical data!</p>");

        } else {
            testList.forEach(e -> {
                html.append("<div class=\"log-entry\" ><a href=\"#\" target=\"_blank\" onclick=\"return false;\"> " + e.getMsg() + ":   " + e.getBeanName() + "#" + e.getMethodName() + "    <span style=\"color: rgb(81, 196, 211);\">" + e.getAddTime() + "</span>");
                html.append("</a><input type=\"hidden\"  value='" + e.getRequestData() + "\'> </div>");
                html.append("<br/><br/>");
            });
        }

        return html.toString();
    }
}
